#main.py

import requests
import json
import time
from machine import UART
from wificonnect import wifi_connect

uart1 = UART(2, baudrate=115200, tx=16, rx=17, timeout=10)

def load_config():
    with open('config.json', 'r') as f:
        return json.load(f)

config = load_config()
PHONE_NUMBER = config['phone_number']
STOCK_API_URL = config['stock_api_url']

def send_cmd(command):
    print(f"Sending command: {command}")
    uart1.write(command + '\r\n')

def ping():
    send_cmd('AT')

def call_phone(phnum=PHONE_NUMBER):
    if len(phnum) != 11:
        print("Wrong phone number, not 11 digits long")
        return
    print(f"Making a call to: {phnum}")
    send_cmd(f'ATD{phnum};')
    time.sleep(30)
    off_call()

def off_call():
    send_cmd('AT+CHUP')
    print("Phone call ended")

def fetch_stock_price():
    try:
        response = requests.get(STOCK_API_URL)
        data = response.json()
        p_value = float(data['p'])
        print(f"Current price: {p_value}")
        return p_value
    except Exception as e:
        print(f"Error fetching stock price: {e}")
        return None

last_p_value = None

def monitor_stock():
    global last_p_value
    while True:
        current_p_value = fetch_stock_price()
        if current_p_value is not None:
            if last_p_value is not None and current_p_value > last_p_value:
                call_phone()
            last_p_value = current_p_value
        time.sleep(300)

if __name__ == "__main__":
    print("Connecting to Wi-Fi...")
    if wifi_connect():
        print("Wi-Fi connected. Monitoring stock prices...")
        ping()
        monitor_stock()
    else:
        print("Wi-Fi connection failed.")


